<template>
  <div class="home-container">
    <div class="statistics-section">
      <el-card class="stat-card">
        <div class="stat-content" @click="goToAreaManagement" style="cursor: pointer;">
          <div class="stat-number">{{ areaCount }}</div>
          <div class="stat-label">已配置区域</div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content" @click="goToDeviceManagement" style="cursor: pointer;">
          <div class="stat-number">{{ deviceCount }}</div>
          <div class="stat-label">已配置设备</div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content" @click="goToDatabaseConfig" style="cursor: pointer;">
          <div class="stat-number">{{ databaseCount }}</div>
          <div class="stat-label">已配置数据库</div>
        </div>
      </el-card>
    </div>
    
    <el-card class="recent-activities" v-if="recentActivities.length > 0">
      <div slot="header" class="card-header">
        <span>最近活动</span>
      </div>
      <el-table :data="recentActivities" stripe style="width: 100%">
        <el-table-column prop="type" label="类型" width="100"></el-table-column>
        <el-table-column prop="message" label="描述"></el-table-column>
        <el-table-column prop="time" label="时间" width="180"></el-table-column>
      </el-table>
    </el-card>
    
    <!-- 可视化大屏 -->
    <el-card class="visualization-card">
      <div slot="header" class="card-header">
        <span>系统拓扑图</span>
      </div>
      <div class="visualization-content">
        <div id="topologyChart" style="width: 100%; height: 600px;"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
// 导入echarts
import * as echarts from 'echarts';

export default {
  name: 'Home',
  data() {
    return {
      areaCount: 0,
      deviceCount: 0,
      databaseCount: 0,
      recentActivities: [
        // 这里可以填充最近活动数据
      ],
      // 存储完整数据用于图表展示
      areas: [],
      devices: [],
      databases: []
    };
  },
  methods: {
    goToAreaManagement() {
      this.$router.push('/area-management');
    },
    goToDeviceManagement() {
      this.$router.push('/device-management');
    },
    goToDatabaseConfig() {
      this.$router.push('/database-config');
    },
    goToDataMigration() {
      // 这里可以添加跳转到数据迁移页面的逻辑
      this.$message.info('数据迁移功能正在开发中');
    },
    loadStatistics() {
      // 从服务器加载统计数据
      Promise.all([
        this.$api.areaApi.getAll(),
        this.$api.deviceApi.getAll(),
        this.$api.databaseConfigApi.getAll()
      ]).then(([areasRes, devicesRes, databasesRes]) => {
        // 处理区域数据
        // http.js已经处理了响应格式，直接获取data部分
        const areasData = areasRes && areasRes.data || [];
        const devicesData = devicesRes && devicesRes.data || [];
        const databasesData = databasesRes && databasesRes.data || [];
        
        // 处理区域数据
        if (Array.isArray(areasData)) {
          this.areas = areasData;
          this.areaCount = areasData.length;
        } else {
          this.areas = [];
          this.areaCount = 0;
        }
        
        // 处理设备数据
        if (Array.isArray(devicesData)) {
          this.devices = devicesData;
          this.deviceCount = devicesData.length;
        } else {
          this.devices = [];
          this.deviceCount = 0;
        }
        
        // 处理数据库配置数据
        if (Array.isArray(databasesData)) {
          this.databases = databasesData;
          this.databaseCount = databasesData.length;
        } else {
          this.databases = [];
          this.databaseCount = 0;
        }
        
        // 数据加载完成后初始化图表
        this.initTopologyChart();
      }).catch(err => {
        console.error('加载数据失败:', err);
        this.$message.error('加载数据失败');
        
        this.areas = [];
        this.devices = [];
        this.databases = [];
        
        this.areaCount = 0;
        this.deviceCount = 0;
        this.databaseCount = 0;
        
        // 初始化图表（空数据状态）
        this.initTopologyChart();
      });
    },
    
    // 初始化拓扑图
    initTopologyChart() {
      const chartDom = document.getElementById('topologyChart');
      const myChart = echarts.init(chartDom);
      
      // 构建节点和边
      const nodes = [];
      const links = [];
      
      // 添加区域节点
      this.areas.forEach(area => {
        nodes.push({
          id: 'area_' + area.id,
          name: area.areaName,
          symbolSize: 60,
          category: 0,
          value: this.devices.filter(d => d.areaId === area.id).length
        });
      });
      
      // 添加设备节点
      this.devices.forEach(device => {
        nodes.push({
          id: 'device_' + device.id,
          name: device.deviceName,
          symbolSize: 40,
          category: 1,
          value: this.databases.filter(db => db.deviceId === device.id).length
        });
        
        // 添加区域到设备的边
        links.push({
          source: 'area_' + device.areaId,
          target: 'device_' + device.id
        });
      });
      
      // 添加数据库节点
      this.databases.forEach(database => {
        nodes.push({
          id: 'db_' + database.id,
          name: database.configName,
          symbolSize: 20,
          category: 2
        });
        
        // 添加设备到数据库的边
        links.push({
          source: 'device_' + database.deviceId,
          target: 'db_' + database.id
        });
      });
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.category === 0) {
              return params.name + '<br/>设备数: ' + params.value;
            } else if (params.category === 1) {
              return params.name + '<br/>数据库数: ' + params.value;
            }
            return params.name;
          }
        },
        legend: [
          {
            data: ['区域', '设备', '数据库'],
            bottom: 10
          }
        ],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            layout: 'force',
            force: {
              repulsion: 1000,
              edgeLength: [80, 120]
            },
            roam: true,
            label: {
              show: true,
              position: 'inside',
              formatter: '{b}',
              fontSize: 12
            },
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [4, 8],
            edgeLabel: {
              fontSize: 12
            },
            data: nodes,
            links: links,
            categories: [
              {
                name: '区域',
                itemStyle: {
                  color: '#ff7875'
                }
              },
              {
                name: '设备',
                itemStyle: {
                  color: '#5cdbd3'
                }
              },
              {
                name: '数据库',
                itemStyle: {
                  color: '#597ef7'
                }
              }
            ],
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 响应窗口大小变化
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    }
  },
  mounted() {
    // 页面加载时加载统计数据
    this.loadStatistics();
  }
};
</script>

<style scoped>
.home-container {
  padding: 0;
}

.welcome-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.card-body {
  padding: 20px;
}

.features-list {
  margin: 20px 0;
}

.features-list ul {
  list-style: none;
  padding-left: 0;
}

.features-list li {
  padding: 10px 0;
  display: flex;
  align-items: center;
}

.features-list i {
  color: #67c23a;
  margin-right: 10px;
}

.quick-actions {
  margin-top: 20px;
}

.statistics-section {
  display: flex;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  margin-right: 20px;
  text-align: center;
}

.stat-card:last-child {
  margin-right: 0;
}

.stat-content {
  padding: 20px;
  transition: all 0.3s ease;
}

.stat-content:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 16px;
  color: #606266;
}

.recent-activities {
  margin-top: 20px;
}

.visualization-card {
  margin-top: 20px;
}

.visualization-content {
  padding: 20px;
}
</style>